package com.zhousoft.blog.velocity;

import java.io.File;
import java.net.URL;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.freeocs.commons.page.Page;
import org.freeocs.commons.util.RequestUtils;
import org.freeocs.commons.util.StringUtils;
import org.freeocs.commons.velocity.VelocityTool;

import com.zhousoft.blog.dao.BlogsDao;
import com.zhousoft.blog.dao.CategoriesDao;
import com.zhousoft.blog.entity.Blogs;
import com.zhousoft.blog.entity.Categories;
import com.zhousoft.blog.entity.SiteBean;

/**
 * FOCSBLOG的Toolbox类
 * 
 * @author chirs
 */
public class FOCSBLOG_VelocityTool extends VelocityTool {

	private Log log = LogFactory.getLog(this.getClass());

	/**
	 * 该属性对应velocity-toolbox.xml中的配置
	 */
	private boolean saveRefer = true;

	public SiteBean site(int id) {
		return new SiteBean();
	}

	public Page<Blogs> blogs(final int pageNo, final int pageSize) {
		return BlogsDao.blogs(pageNo, pageSize);
	}

	public List<Categories> categories() {
		return CategoriesDao.categories();
	}

	/**
	 * 获取FCKUpload过程中生成的会话ID
	 * 
	 * @return
	 */
	public String dlog_session_id(HttpServletRequest req) {
		return RequestUtils.getFocsSessionId(req);
	}

	/**
	 * 获取一个全路径的文件名部分
	 * 
	 * @param absolute_path
	 * @return
	 */
	public String file_name(String absolute_path) {
		return StringUtils.substringAfterLast(absolute_path, File.separator);
	}

	/**
	 * 记录外部网站引用
	 * 
	 * @param site
	 * @param ref_id
	 * @param ref_type
	 * @param req
	 */
	public void save_refer(SiteBean site, int ref_id, int ref_type, HttpServletRequest req) {
		if (!saveRefer)
			return;
		String refer = RequestUtils.getHeader(req, "refer");
		if (StringUtils.isNotEmpty(refer)) {
			URL url;
			try {
				url = new URL(refer);
				String host = url.getHost();
				if (!StringUtils.equals(req.getServerName(), host)) {

				}
			} catch (Exception e) {
				log.error("Save refer failed, ip=" + req.getRemoteAddr() + ",refer=" + refer, e);
			} finally {
				url = null;
			}
		}
	}

	/**
	 * 显示时间(diary.vm)
	 * 
	 * @param year
	 * @param month
	 * @param date
	 * @return
	 */
	public String show_time(int year, int month, int date) {
		StringBuffer stime = new StringBuffer();
		if (year > 0 && month > 0 && date > 0) {// 某天
			stime.append(year);
			stime.append('.');
			stime.append(month);
			stime.append('.');
			stime.append(date);
		} else if (year > 0 && month > 0) {// 某月
			stime.append(year);
			stime.append('.');
			stime.append(month);
		} else if (year > 0) {// 某年
			stime.append(year);
		}
		return stime.toString();
	}

	/**
	 * 构造日历(_catalog_and_calendar.vm)
	 * 
	 * @param year
	 * @param month
	 * @return
	 */
	public int[][] calendar(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month - 1);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		int firstDateInWeek = cal.get(Calendar.DAY_OF_WEEK) - 1;
		int dateOfMonth = getMonthDateCount(cal);
		int base = dateOfMonth + firstDateInWeek;
		int row = base / 7;
		row += ((base % 7) > 0) ? 1 : 0;
		int[][] cals = new int[row][7];
		int iCol = firstDateInWeek, iRow = 0;
		for (int i = 1; i <= dateOfMonth; i++) {
			cals[iRow][iCol] = i;
			if (iCol == 6) {
				iCol = 0;
				iRow++;
			} else
				iCol++;
		}
		return cals;
	}

	/**
	 * 得到指定月份的天数
	 * 
	 * @param cal
	 * @return
	 */
	private static int getMonthDateCount(Calendar cal) {
		Calendar cal2 = (Calendar) cal.clone();
		cal2.add(Calendar.MONTH, 1);
		cal2.set(Calendar.DAY_OF_MONTH, 1);
		cal2.add(Calendar.DAY_OF_MONTH, -1);
		return cal2.get(Calendar.DAY_OF_MONTH);
	}

	/**
	 * (_catalog_and_calendar.vm)
	 * 
	 * @param field
	 * @return
	 */
	public int calendar(int field) {
		Calendar cal = Calendar.getInstance();
		String param;
		int defValue;
		switch (field) {
		case 1:
			param = "year";
			defValue = cal.get(Calendar.YEAR);
			break;
		case 2:
			param = "month";
			defValue = cal.get(Calendar.MONTH) + 1;
			break;
		case 3:
			param = "date";
			defValue = cal.get(Calendar.DATE);
			break;
		default:
			return -1;
		}
		return RequestUtils.getParam(request, param, defValue);
	}

	/**
	 * 根据时间参数组合URL (diary.vm)
	 * 
	 * @param year
	 * @param month
	 * @param date
	 * @return
	 */
	public String make_date_params(String param_name, int cat_id, int year, int month, int date) {
		StringBuffer param = new StringBuffer();
		if (cat_id > 0) {
			param.append('&');
			param.append(param_name);
			param.append('=');
			param.append(cat_id);
		}
		if (year > 0) {
			param.append("&year=");
			param.append(year);
		}
		if (month > 0) {
			param.append("&month=");
			param.append(month);
		}
		if (date > 0) {
			param.append("&date=");
			param.append(date);
		}
		return param.toString();
	}

	/**
	 * 对较长的文本内容进行切割
	 * 
	 * @param content
	 * @param page
	 * @param word_count
	 * @return
	 */
	public String split(String content, int page, int word_count) {
		int fromIdx = (page - 1) * word_count;
		int endIdx = fromIdx + word_count;
		if (fromIdx >= content.length())
			return "";
		if (endIdx > content.length())
			endIdx = content.length();
		return content.substring(fromIdx, endIdx);
	}

	/** parameter getter/setter */
	public boolean isSaveRefer() {
		return saveRefer;
	}

	public void setSaveRefer(boolean saveRefer) {
		this.saveRefer = saveRefer;
	}
}
